// Copyright 2012 Google Inc. All Rights Reserved.

package com.google.appengine.syncserver.entities;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Transaction;

/**
 * Generates client ids. Android client ids are not unique so 
 * we generate client ids on the server.
 */
public class ClientIdGenerator {

  /**
   * Call to this function returns an unique client id.
   * 
   * @param username
   * @return The next unique client id.
   */
  public static long getNextClientId(String username) {

    Key key = EntityKeyFactory.getUserMetadataKey(username);
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Transaction transaction = datastore.beginTransaction();

    Entity entity;
    try {
      entity = datastore.get(transaction, key);
    } catch (EntityNotFoundException e) {
      entity = new Entity(key);
    }

    UserMetadata metadata = new UserMetadata(entity);

    long clientId = metadata.incrementMaxClientId();

    // Since we have changed the metadata by incrementing client id we need to
    // put back the entity in the datastore.
    datastore.put(transaction, metadata.getEntity());
    transaction.commit();

    return clientId;
  }
}
